package com.ellecity06.cwhiskymall.ui.newer

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.cwhiskymall.bean.request.ClassifyRightRequest
import com.ellecity06.cwhiskymall.http.request
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/11/13 14:55
 * @des
 */
class NewerGoodViewModel : BaseMviViewModel<NewerGoodState, NewerGoodIntent>() {
    override suspend fun collectIntent(it: NewerGoodIntent) { when (it) {
            is NewerGoodIntent.FetchGood -> {
                pagerHelper.pageIndex = 1
                fetchGood(it.id)
            }
        is NewerGoodIntent.LoadMore ->fetchGood(it.id)
    }
    }

    private fun fetchGood(id: Int) {
        val request = ClassifyRightRequest(id)
        request.pageNum = pagerHelper.pageIndex
        request.pageSize = 10
        request(success = {
                if (it?.records != null) {
                    if (!it.records.isNullOrEmpty()) {
                        val hasMore = it.records!!.size >= request.pageSize
                        if (pagerHelper.pageIndex == 1) {
                            mState.postEvent(NewerGoodState.RefreshSuccess(it.records!!, hasMore))
                        } else {
                            mState.postEvent(NewerGoodState.LoadMoreSuccess(it.records!!, hasMore))
                        }
                        pagerHelper.pageIndex++
                    } else {
                        if (pagerHelper.pageIndex == 1) {
                            mState.postEvent(NewerGoodState.RefreshSuccess(mutableListOf(), false))
                        } else {
                            mState.postEvent(NewerGoodState.NoMore)
                        }
                    }
                }

            },
            api = { getClassifyRightList(request) }, error = {
                viewModelScope.launch { mState.postEvent(NewerGoodState.LoadError) }

            })
    }
}